//- Copyright (C) 2023 Beijing Huaxia Chunsong Technology Co., Ltd. 
//- <https://www.chatopera.com>, Licensed under the Chunsong Public 
//- License, Version 1.0  (the "License"), https://docs.cskefu.com/licenses/v1.html
//- Unless required by applicable law or agreed to in writing, software
//- distributed under the License is distributed on an "AS IS" BASIS,
//- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//- See the License for the specific language governing permissions and
//- limitations under the License.
//- Copyright (C) 2018-Jun. 2023 Chatopera Inc, <https://www.chatopera.com>
//- Licensed under the Apache License, Version 2.0
//- http://www.apache.org/licenses/LICENSE-2.0
extends /apps/entim/include/layout.pug

block content
    style.
        * {
            margin: 0;
            padding: 0;
            -webkit-touch-callout: none; /* iOS Safari */
            -webkit-user-select: none; /* Chrome/Safari/Opera */
            -khtml-user-select: none; /* Konqueror */
            -moz-user-select: none; /* Firefox */
            -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently	not supported by any browser */
        }
    #header
        .ukefu-entim-info
            .ukefu-entim-user
                | #{user.uname}
                span.ukefu-entim-status.online(title='在线')
                    i.layui-icon 
            .ukefu-entim-desc
                input.ukefu-entim-remark(placeholder='编辑签名', value='用心沟通，成就客户')
            .ukefu-entim-close
                a(href='javascript:void(0)', onclick='top.closeentim()')
                    i.layui-icon ဆ
    #containter.clearfix
        .layui-tab.layui-tab-brief
            ul.layui-tab-title.ukefu-entim-type
                li.layui-this
                    i.layui-icon 
                li
                    i.layui-icon 
                li
                    i.layui-icon 
            .layui-tab-content(style='height:350px;overflow-y:auto;padding: 0px 10px;')
                .layui-tab-item.layui-show
                    ul#frends
                        if organList
                            for organ in organList
                                li.ukefu-entim-organ-open
                                    h5.ukefu-entim-organ(lay-filter="spread" lay-type="true")
                                        i.layui-icon 
                                        span= organ.name
                                        - var curusers = 0
                                        if userList
                                            for entimuser in userList
                                                if entimuser.organs && entimuser.id != user.id && entimuser.organs[organ.id]
                                                    - curusers = curusers+1
                                        em
                                            | (
                                            cite.layim-count= curusers
                                            | )

                                    ul.ukefu-user-list
                                        if userList
                                            for entimuser in userList
                                                if entimuser.organs && entimuser.id != user.id && entimuser.organs[organ.id]
                                                    li(id="user_#{entimuser.id}")
                                                        a(href="javascript:void(0)", onclick="openchat('/ent/im/chat.html?userid=#{entimuser.id}' , '/images/user-pc.png' , '#{entimuser.uname}' , '#{entimuser.id}' , '最近登陆:#{pugHelper.formatDate('yyyy-MM-dd HH:mm:ss', entimuser.lastlogintime)}');")
                                                            img(src="/images/user-pc.png")
                                                            span= entimuser.uname
                                                            p
                                                                | 最近登陆:#{pugHelper.formatDate('yyyy-MM-dd HH:mm:ss', entimuser.lastlogintime)}
                                                        - var newmsg = 0
                                                        if recentUserList
                                                            for recentUser in recentUserList
                                                                if recentUser.user.id == entimuser.id
                                                                    - newmsg = recentUser.newmsg
                                                        div(class="ukefu-session-tip cont_#{entimuser.id}", data-newmsg=newmsg, style="#{newmsg > 0 ? 'display:block' : ''}")
                .layui-tab-item#imgroup
                    include /apps/entim/group/grouplist.pug
                .layui-tab-item
                    ul.ukefu-user-list(style='display:block;')
                        if recentUserList
                            for recentUser in recentUserList
                                li(id="recentuser_#{recentUser.id}")
                                    a(href="javascript:void(0)", onclick="openchat('/ent/im/chat.html?userid=#{recentUser.user.id}' , '/images/user-pc.png' , '#{recentUser.user.uname}' , '#{recentUser.user.id}' , '最近登陆:#{pugHelper.formatDate('yyyy-MM-dd HH:mm:ss', recentUser.user.lastlogintime)}');")
                                        img(src="/images/user-pc.png")
                                        span= recentUser.user.uname
                                        p
                                            if recentUser.lastmsg
                                                | !{recentUser.lastmsg}
                                            else
                                                | 最近登陆：#{pugHelper.formatDate('yyyy-MM-dd HH:mm:ss', recentUser.user.lastlogintime)}
                                    .ukefu-session-tip(class="cont_#{recentUser.user.id}", data-newmsg=recentUser.newmsg, style="#{recentUser.newmsg > 0 ? 'display:block' : ''}")= recentUser.newmsg
    #footer
        ul.ukefu-entim-tool
            li.layui-icon(title='搜索', onclick='search();') 
            li.layui-icon.ukefu-entim-msgbox(title='消息盒子')
                - var newmsg = 0
                if recentUserList
                    for recentUser in recentUserList
                        - newmsg = recentUser.newmsg + newmsg
                | 
                span.layui-anim.layer-anim-05.animated#msgbox(data-newmsg=newmsg, style="#{newmsg == 0 ? 'display:none' : ''}")= newmsg
            if user && (user.roleAuthMap["A14_A01"] || user.admin)
                li.layui-icon(title="新建", onclick="newGroup()")
                    | 
            li.layui-icon(title='更换背景', onclick='skin()') 
    //  <li class="layui-icon" title="关于" onclick="about()"></li>
    script.
        layui.use('element', function () {
            var $ = layui.jquery
                , element = layui.element(); //Tab的切换功能，切换事件监听等，需要依赖element模块
        });
        function newGroup() {
            layer.prompt({
                title: '新建一个群',
                offset: 'b',
                formType: 0
            }, function (text, index) {
                layer.close(index);
                loadURL('/ent/im/group/save.html?name=' + encodeURIComponent(text), '#imgroup')
            })
        };

        function about() {
            layer.open({
                title: '关于',
                btn: '关闭',
                shade: 0,
                content: '<span id="welcome-message"><p>欢迎使用春松客服企业聊天</p><p>QQ群：<a target="_blank" href="https://jq.qq.com/?_wv=1027&k=5I1cJLP"><img border="0" src="//pub.idqqimg.com/wpa/images/group.png" alt="春松客服开源社区" title="春松客服开源社区"></a></p><p>详情请咨询：<a href="https://www.chatopera.com" target="_blank" style="color:#32c24d;">春松客服</a></p></span>'
            });
        }
        function search() {
            layer.open({
                title: '查询用户',
                type: 1
                ,
                id: 'search'
                ,
                offset: 'b' //具体配置参考：offset参数项
                ,
                content: '<div><div id="" class="layui-layer-content ukefu-entim-search"><input type="text" id="frend_search" class="layui-layer-input" value=""></div></div>'
                ,
                btn: '关闭'
                ,
                shade: 0 //不显示遮罩
                ,
                yes: function () {
                    layer.closeAll();
                }
                ,
                end: function () {
                    $("#frends li").show();
                }
            });
            $('#frend_search').on('input', function () {
                $('#frends li').addClass("ukefu-entim-organ-open");
                if ($.trim($(this).val()) != "") {
                    $("#frends li").hide().filter(":contains('" + $(this).val() + "')").show();
                } else {
                    $("#frends li").show();
                }
            })
        }
        function skin() {
            layer.open({
                title: '选择风格',
                type: 2
                , id: 'selskin'
                , content: '/ent/im/skin.html'
                , btn: '关闭'
                , shade: 0 //不显示遮罩
            });
        }
        function escapeHtml (str) {
            if (typeof str == 'string') {
                return str.replace(/<|&|>/g, function (matches) {
                    return ({
                        '<': '&lt;',
                        '>': '&gt;',
                        '&': '&amp;'
                    })[matches];
                });
            }

            return '';
        }
        function openchat(url, img, name, id, text) {
            top.layer.open({
                type: 2,
                id: id,
                title: ["<div style='position: relative;height: 42px;padding: 5px 15px 5px 0px;line-height: 20px;cursor: pointer;display: inline-block;vertical-align: top;' id='dialog_" + id + "'><img src='" + img + "' style='max-height:50px;'><div style='padding:0px 5px;line-height: 23px;display: inline-block;vertical-align: top;'><span style='vertical-align: top;font-size:18px;'>" + escapeHtml(name) + "<span class='ukefu-entim-status offline' id='chat_" + id + "' title='离线'><i class='layui-icon'></i></span></span><p style='vertical-align: top;font-size: 12px;color: #999;'>" + text + "</p></div></div>", "height:55px"],
                closeBtn: 1, //不显示关闭按钮
                shade: false,
                area: ['700px', '520px'],
                maxmin: true,
                anim: 2,
                shade: 0,
                content: url
            });
            top.$('#' + id).next().find("a.layui-layer-maxmin").click();
            if ($('#msgbox').data("msgbox") - $('.cont_' + id).data("newmsg") > 0) {
                $('#msgbox').data("newmsg", $('#msgbox').data("msgbox") - $('.cont_' + id).data("newmsg"));
            } else {
                $('#msgbox').data("newmsg", 0).hide();
            }
            $('.cont_' + id).data("newmsg", 0).hide();
        }
        $('.ukefu-entim-organ').click(function () {
            if ($(this).parent().hasClass('ukefu-entim-organ-open')) {
                $(this).parent().removeClass('ukefu-entim-organ-open');
                $(this).children().first().html('&#xe602;');
            } else {
                $(this).parent().addClass('ukefu-entim-organ-open')
                $(this).children().first().html('&#xe61a;');
            }
        });
        var socket = io.connect(location.protocol + "//" + top.hostname + ":" + top.port + "/im/ent?userid=#{user.id}");
        socket.on('connect', function () {
            //service.sendRequestMessage();
            //output('<span id="callOutConnect-message">'+ new Date().format("yyyy-MM-dd hh:mm:ss") + ' 开始沟通' +'</span>' , 'message callOutConnect-message');
        })
        socket.on('message', function (data) {
            if (top.$('#dialog_' + data.contextid).length == 0) {
                var user;
                if ($('.cont_' + data.contextid).length > 0) {
                    user = $('.cont_' + data.contextid)[0];
                }
                if ($(user).data('newmsg')) {
                    $('.cont_' + data.contextid).data('newmsg', $(user).data('newmsg') + 1).text($(user).data('newmsg'));
                } else {
                    $('.cont_' + data.contextid).data('newmsg', 1).text($(user).data('newmsg'));
                }
                $('.cont_' + data.contextid).show();
                $('#msgbox').data("newmsg", $('#msgbox').data("newmsg") + 1).text($('#msgbox').data("newmsg")).show();
            }
        });
        socket.on('status', function (data) {

        })
        socket.on('disconnect', function () {
        });

